<template>
  <div class="user-management">
    <n-card title="用户管理" :bordered="false" size="small" class="h-full shadow-sm rounded-8px">
      <!-- 搜索区域 -->
      <n-space class="pb-12px" justify="space-between">
        <n-space>
          <n-input
            v-model:value="searchParams.keyword"
            placeholder="搜索用户手机号"
            clearable
            class="w-200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <icon-park-outline-search class="text-16px" />
            </template>
          </n-input>
          <n-select
            v-model:value="searchParams.is_active"
            placeholder="用户状态"
            clearable
            class="w-120px"
            :options="statusOptions"
          />
          <n-date-picker
            v-model:value="searchParams.dateRange"
            type="daterange"
            placeholder="注册时间范围"
            clearable
            class="w-240px"
          />
          <n-button type="primary" @click="handleSearch">搜索</n-button>
          <n-button @click="handleReset">重置</n-button>
        </n-space>
        <n-space>
          <n-button @click="handleExport">
            <template #icon>
              <icon-park-outline-download />
            </template>
            导出数据
          </n-button>
        </n-space>
      </n-space>

      <!-- 统计卡片 -->
      <n-grid :cols="4" :x-gap="16" class="mb-16px">
        <n-grid-item>
          <n-statistic label="总用户数" :value="statistics.total" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="活跃用户" :value="statistics.active" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="今日新增" :value="statistics.todayNew" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="本月新增" :value="statistics.monthNew" />
        </n-grid-item>
      </n-grid>

      <!-- 表格 -->
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :row-key="(row) => row.id"
        remote
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </n-card>

    <!-- 用户详情弹窗 -->
    <n-modal v-model:show="detailVisible" preset="dialog" title="用户详情" style="width: 90%; max-width: 1200px;">
      <div v-if="currentUser" class="space-y-16px">
        <n-grid :cols="25" :x-gap="20">
          <!-- 第一列：基本信息 -->
          <n-grid-item :span="10">
            <div class="pr-4">
              <h4 class="text-14px font-semibold mb-8px">基本信息</h4>
              <n-descriptions :column="2" bordered size="small" label-style="width: 80px; font-weight: 500;">
                <n-descriptions-item label="用户ID">
                  {{ currentUser.id }}
                </n-descriptions-item>
                <n-descriptions-item label="手机号">
                  {{ currentUser.phone }}
                </n-descriptions-item>
                <n-descriptions-item label="注册渠道">
                  {{ currentUser.register_channel || '-' }}
                </n-descriptions-item>
                <n-descriptions-item label="注册时间">
                  {{ formatTime(currentUser.created_at) }}
                </n-descriptions-item>
                <n-descriptions-item label="最后登录">
                  {{ formatTime(currentUser.last_login_at) || '-' }}
                </n-descriptions-item>
                <n-descriptions-item label="登录IP">
                  {{ currentUser.last_login_ip || '-' }}
                </n-descriptions-item>
                <n-descriptions-item label="用户状态">
                  <n-tag :type="currentUser.is_active ? 'success' : 'error'" size="small">
                    {{ currentUser.is_active ? '正常' : '禁用' }}
                  </n-tag>
                </n-descriptions-item>
              </n-descriptions>
            </div>
          </n-grid-item>

          <!-- 第二列：用户额度和兑换操作 -->
          <n-grid-item :span="15">
            <div class="pl-4">
              <div class="flex justify-between items-center mb-8px">
                <h4 class="text-14px font-semibold">用户额度</h4>
                <n-button type="warning" size="small" @click="handleShowRedeemModal(currentUser)">
                  兑换码兑换
                </n-button>
              </div>

              <div v-if="currentUser.quotas && currentUser.quotas.length > 0">
                <n-data-table
                  :columns="quotaColumns"
                  :data="currentUser.quotas"
                  :pagination="false"
                  size="small"
                />
              </div>
              <div v-else class="text-center py-8 text-gray-500">
                暂无额度信息
              </div>
            </div>
          </n-grid-item>
        </n-grid>
      </div>
      <template #action>
        <n-space>
          <n-button @click="detailVisible = false">关闭</n-button>
          <n-button type="primary" @click="handleViewOrders(currentUser)">查看订单</n-button>
          <n-button type="primary" @click="handleViewQuestions(currentUser)">查看问答</n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 兑换码兑换弹窗 -->
    <n-modal v-model:show="redeemModalVisible" preset="dialog" title="给用户兑换兑换码">
      <div v-if="selectedUser" class="space-y-16px">
        <n-alert type="info" :show-icon="false">
          为用户 <strong>{{ selectedUser.phone }}</strong> 兑换兑换码
        </n-alert>

        <n-form ref="redeemFormRef" :model="redeemForm" :rules="redeemRules">
          <n-form-item label="选择兑换码" path="redeem_code_id">
            <n-select
              v-model:value="redeemForm.redeem_code_id"
              placeholder="请选择要兑换的兑换码"
              :options="redeemCodeOptions"
              :loading="loadingRedeemCodes"
              clearable
              filterable
              @focus="fetchAvailableRedeemCodes"
              @update:value="handleRedeemCodeChange"
            />
          </n-form-item>
        </n-form>

        <div v-if="selectedRedeemCode" class="p-12px bg-gray-50 rounded-4px">
          <h4 class="text-14px font-semibold mb-8px">兑换码详情</h4>
          <n-descriptions :column="2" size="small">
            <n-descriptions-item label="兑换码">
              {{ selectedRedeemCode.code }}
            </n-descriptions-item>
            <n-descriptions-item label="额度类型">
              <n-tag :type="getQuotaTypeColor(selectedRedeemCode.quota_type)">
                {{ getQuotaTypeName(selectedRedeemCode.quota_type) }}
              </n-tag>
            </n-descriptions-item>
            <n-descriptions-item label="目标">
              {{ getTargetName(selectedRedeemCode) }}
            </n-descriptions-item>
            <n-descriptions-item label="可兑换次数">
              {{ selectedRedeemCode.redeem_count }}
            </n-descriptions-item>
            <n-descriptions-item label="过期时间">
              {{ selectedRedeemCode.expires_at ? formatTime(selectedRedeemCode.expires_at) : '永不过期' }}
            </n-descriptions-item>
          </n-descriptions>
        </div>
      </div>
      <template #action>
        <n-space>
          <n-button @click="handleCloseRedeemModal">取消</n-button>
          <n-button
            type="primary"
            :loading="redeemLoading"
            :disabled="!redeemForm.redeem_code_id"
            @click="handleConfirmRedeem"
          >
            确认兑换
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h, computed } from 'vue'
import type { DataTableColumns } from 'naive-ui'
import { NButton, NTag, NSpace, useMessage } from 'naive-ui'
import { formatTime } from '@/utils/time'
import { userApi } from '@/service/api/bizhi'
import { useRouter } from 'vue-router'

const message = useMessage()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const detailVisible = ref(false)
const tableData = ref([])
const currentUser = ref(null)

// 兑换码相关
const redeemModalVisible = ref(false)
const selectedUser = ref(null)
const loadingRedeemCodes = ref(false)
const redeemLoading = ref(false)
const redeemFormRef = ref(null)
const availableRedeemCodes = ref([])

const redeemForm = reactive({
  redeem_code_id: null
})

const redeemRules = {
  redeem_code_id: [
    {
      required: true,
      message: '请选择兑换码',
      trigger: ['change', 'blur'],
      type: 'number'
    }
  ]
}

// 搜索参数
const searchParams = reactive({
  keyword: '',
  is_active: null,
  dateRange: null,
  page: 1,
  limit: 20
})

// 统计数据
const statistics = reactive({
  total: 0,
  active: 0,
  todayNew: 0,
  monthNew: 0
})

// 状态选项
const statusOptions = [
  { label: '正常', value: true },
  { label: '禁用', value: false }
]

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 20,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100]
})

// 表格列配置
const columns: DataTableColumns = [
  { title: 'ID', key: 'id', width: 80 },
  { title: '手机号', key: 'phone', width: 120 },
  { title: '注册渠道', key: 'register_channel', width: 100 },
  {
    title: '用户状态',
    key: 'is_active',
    width: 100,
    render: (row: any) => {
      return h(NTag, {
        type: row.is_active ? 'success' : 'error'
      }, {
        default: () => row.is_active ? '正常' : '禁用'
      })
    }
  },
  {
    title: '最后登录',
    key: 'last_login_at',
    width: 180,
    render: (row: any) => formatTime(row.last_login_at)
  },
  {
    title: '注册时间',
    key: 'created_at',
    width: 180,
    render: (row: any) => formatTime(row.created_at)
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    render: (row: any) => {
      return h(NSpace, {}, {
        default: () => [
          h(NButton, {
            size: 'small',
            type: 'primary',
            onClick: () => handleViewDetail(row)
          }, { default: () => '查看详情' }),
          h(NButton, {
            size: 'small',
            type: row.is_active ? 'error' : 'success',
            onClick: () => handleToggleStatus(row)
          }, { default: () => row.is_active ? '禁用' : '启用' })
        ]
      })
    }
  }
]

// 额度表格列配置
const quotaColumns: DataTableColumns = [
  { title: '额度类型', key: 'quota_type', width: 100 },
  { title: '目标', key: 'target_name', width: 120 },
  { title: '总次数', key: 'total_count', width: 80 },
  { title: '已使用', key: 'used_count', width: 80 },
  { title: '剩余', key: 'remaining_count', width: 80 },
  { title: '过期时间', key: 'expires_at', width: 180 }
]

// 兑换码选项
const redeemCodeOptions = computed(() => {
  return availableRedeemCodes.value.map(code => ({
    label: `${code.code} - ${getQuotaTypeName(code.quota_type)} - ${code.redeem_count}次`,
    value: code.id
  }))
})

// 选中的兑换码
const selectedRedeemCode = computed(() => {
  if (!redeemForm.redeem_code_id) return null
  return availableRedeemCodes.value.find(code => code.id === redeemForm.redeem_code_id)
})

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const response = await userApi.getUserStats()
    if (response.code === 200) {
      Object.assign(statistics, response.data)
    } else {
      message.error(response.message || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    message.error('获取统计数据失败')
  }
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: searchParams.page,
      limit: searchParams.limit,
      keyword: searchParams.keyword || undefined,
      is_active: searchParams.is_active !== null ? searchParams.is_active : undefined
    }

    // 处理日期范围
    if (searchParams.dateRange && searchParams.dateRange.length === 2) {
      params.start_date = new Date(searchParams.dateRange[0]).toISOString().split('T')[0]
      params.end_date = new Date(searchParams.dateRange[1]).toISOString().split('T')[0]
    }

    const response = await userApi.getUserList(params)
    if (response.code === 200) {
      tableData.value = response.data.list || []
      pagination.itemCount = response.data.pagination?.total || 0
      pagination.page = response.data.pagination?.page || 1
      pagination.pageSize = response.data.pagination?.limit || 20
    } else {
      message.error(response.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 查看详情
const handleViewDetail = async (row: any) => {
  try {
    const response = await userApi.getUserDetail(row.id)
    if (response.code === 200) {
      currentUser.value = response.data.user
      detailVisible.value = true
    } else {
      message.error(response.message || '获取用户详情失败')
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
    message.error('获取用户详情失败')
  }
}

// 切换用户状态
const handleToggleStatus = async (row: any) => {
  try {
    // TODO: 调用API切换状态
    row.is_active = !row.is_active
    message.success(`用户已${row.is_active ? '启用' : '禁用'}`)
  } catch (error) {
    message.error('操作失败')
  }
}

// 查看订单
const handleViewOrders = (user: any) => {
  if (!user) return

  // 跳转到订单管理页面，只传递用户手机号
  router.push({
    path: '/bizhi/order',
    query: {
      user_phone: user.phone
    }
  })

  // 关闭用户详情弹窗
  detailVisible.value = false

  message.success(`正在查看用户 ${user.phone} 的订单`)
}

// 查看问答
const handleViewQuestions = (user: any) => {
  if (!user) return

  // 跳转到问答管理页面，只传递用户手机号
  router.push({
    path: '/bizhi/question',
    query: {
      user_phone: user.phone
    }
  })

  // 关闭用户详情弹窗
  detailVisible.value = false

  message.success(`正在查看用户 ${user.phone} 的问答记录`)
}

// 导出数据
const handleExport = async () => {
  try {
    // TODO: 调用导出API
    message.success('导出成功')
  } catch (error) {
    message.error('导出失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchParams, {
    keyword: '',
    is_active: null,
    dateRange: null,
    page: 1,
    limit: 20
  })
  fetchData()
}

// 分页变化
const handlePageChange = (page: number) => {
  pagination.page = page
  searchParams.page = page
  fetchData()
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.page = 1
  searchParams.limit = pageSize
  searchParams.page = 1
  fetchData()
}

// 兑换码相关方法
const handleShowRedeemModal = (user: any) => {
  selectedUser.value = user
  redeemModalVisible.value = true
  redeemForm.redeem_code_id = null

  // 延迟清除表单验证状态，确保DOM更新完成
  setTimeout(() => {
    if (redeemFormRef.value) {
      redeemFormRef.value.restoreValidation()
    }
  }, 100)
}

const handleCloseRedeemModal = () => {
  redeemModalVisible.value = false
  selectedUser.value = null
  redeemForm.redeem_code_id = null
  availableRedeemCodes.value = []
  // 清除表单验证状态
  if (redeemFormRef.value) {
    redeemFormRef.value.restoreValidation()
  }
}

const handleRedeemCodeChange = (value: any) => {
  redeemForm.redeem_code_id = value

  // 延迟清除表单验证状态，确保选择器更新完成
  setTimeout(() => {
    if (redeemFormRef.value) {
      redeemFormRef.value.restoreValidation()
    }
  }, 50)
}

const fetchAvailableRedeemCodes = async () => {
  if (availableRedeemCodes.value.length > 0) return

  loadingRedeemCodes.value = true
  try {
    const response = await userApi.getAvailableRedeemCodes()
    if (response.code === 200) {
      availableRedeemCodes.value = response.data.redeemCodes || []
    } else {
      message.error(response.message || '获取可用兑换码失败')
    }
  } catch (error) {
    console.error('获取可用兑换码失败:', error)
    message.error('获取可用兑换码失败')
  } finally {
    loadingRedeemCodes.value = false
  }
}

const handleConfirmRedeem = async () => {
  if (!redeemFormRef.value) return

  // 先检查是否选择了兑换码
  if (!redeemForm.redeem_code_id) {
    message.error('请选择兑换码')
    return
  }

  try {
    await redeemFormRef.value.validate()
    redeemLoading.value = true

    const response = await userApi.redeemCodeForUser(selectedUser.value.id, {
      redeem_code_id: redeemForm.redeem_code_id
    })

    if (response.code === 200) {
      message.success('兑换码兑换成功')

      // 保存用户信息，因为 handleCloseRedeemModal 会清空 selectedUser
      const userToRefresh = selectedUser.value

      handleCloseRedeemModal()

      // 刷新用户详情
      if (currentUser.value && userToRefresh && currentUser.value.id === userToRefresh.id) {
        await handleViewDetail(userToRefresh)
      }
    } else {
      message.error((response as any).message || '兑换码兑换失败')
    }
  } catch (error: any) {
    if (error?.errors) {
      // 表单验证错误
      return
    }
    console.error('兑换码兑换失败:', error)
    message.error('兑换码兑换失败')
  } finally {
    redeemLoading.value = false
  }
}

// 工具方法
const getQuotaTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    general: '通用',
    domain: '领域',
    expert: '专家'
  }
  return typeMap[type] || type
}

const getQuotaTypeColor = (type: string): 'default' | 'info' | 'success' | 'error' | 'primary' | 'warning' => {
  const colorMap: Record<string, 'default' | 'info' | 'success' | 'error' | 'primary' | 'warning'> = {
    general: 'default',
    domain: 'info',
    expert: 'success'
  }
  return colorMap[type] || 'default'
}

const getTargetName = (redeemCode: any) => {
  if (redeemCode.quota_type === 'general') {
    return '通用'
  } else if (redeemCode.quota_type === 'domain' && redeemCode.domain) {
    return redeemCode.domain.name
  } else if (redeemCode.quota_type === 'expert' && redeemCode.expert) {
    return redeemCode.expert.nickname
  }
  return '-'
}

onMounted(() => {
  fetchStatistics()
  fetchData()
})
</script>

<style scoped>
.user-management {
  height: 100%;
}
</style>
